package com.googlecode.grima.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.grima.base.GenericDao;
import com.googlecode.grima.base.GenericEntityService;
import com.googlecode.grima.base.GenericEntityServiceImpl;
import com.googlecode.grima.base.Page;
import com.googlecode.grima.base.SearchResult;
import com.googlecode.grima.base.SearchTemplate;
import com.googlecode.grima.dao.StatusDao;
import com.googlecode.grima.domain.Status;

@Service("statusService")
public class StatusService extends GenericEntityServiceImpl<Status, Long> implements GenericEntityService<Status, Long> {

	protected StatusDao statusDao;

	@Autowired
	public void setStatusDao(StatusDao statusDao) {
		this.statusDao = statusDao;
	}

	@Override
	public GenericDao<Status, Long> getDao() {
		return statusDao;
	}

	@Override
	public Status getNew() {
		return new Status();
	}

	@Override
	public Status getNewWithDefaults() {
		return getNew();
	}
	
	@Override
	@Transactional
	public void save(Status status) {
		super.save(status);
	}
	
	public SearchResult<Status, Long> findAll(Page page){
		SearchResult<Status, Long> ret = new SearchResult<Status, Long>();
    SearchTemplate searchTemplate = new SearchTemplate();

		if (page != null){
			int pageNumber = page.getPageNumber();
			int pageSize = page.getPageSize();
	    int firstResult = ((pageNumber-1) * pageSize);
	    searchTemplate.setFirstResult(firstResult);
	    searchTemplate.setMaxResults(pageSize);
		}
		
		List<Status> statuses = find(searchTemplate);
		int count = findCount(searchTemplate);

		ret.setTotal(count);
		ret.setRows(statuses);
		
		return ret;
	}
	
	public SearchResult<Status, Long> findByParameters(String name, String category, Page page) {
		SearchResult<Status, Long> ret = new SearchResult<Status, Long>();
		
		SearchTemplate searchTemplate = new SearchTemplate();

		if (page != null){
			int pageNumber = page.getPageNumber();
			int pageSize = page.getPageSize();
			
	    int firstResult = ((pageNumber-1) * pageSize);
	    searchTemplate.setFirstResult(firstResult);
	    searchTemplate.setMaxResults(pageSize);
    }    
    
		if (StringUtils.isNotEmpty(name)){
    	searchTemplate.addCriterion(Restrictions.like("name", "%"+name+"%"));
    }

		if (category != null){
    	searchTemplate.addCriterion(Restrictions.eq("category", category));
    }
		
		List<Status> partners = find(searchTemplate);
		int count = findCount(searchTemplate);

		ret.setTotal(count);
		ret.setRows(partners);
		
		return ret;
  }
	
	public void deleteById(Long id){
		deleteByPrimaryKey(id);
	}

}
